﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using WAD.WEB.AppCode;
using WAD.DAL;
using WAD.Model;
using GL.Tools;
using WAD.WEB.AppCode.Sms;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using ZXing;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;

namespace WAD.WEB.Client.Ajax
{
    /// <summary>
    /// User 的摘要说明
    /// </summary>
    public class Qrcode : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "make": this.Make(); break;
                case "decode": this.Decode(); break;
            }
        }
        /// <summary>
        /// 生成二维码
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Make()
        {

            //内容
            String code = Parse.String("code");
            int size = Parse.Int("size", 200);
            Response.ContentType = "image/jpeg";
            Response.Clear();
            Barcode.MakeQrcode(code, size).Save(Response.OutputStream, ImageFormat.Jpeg);
            Response.Flush();
        }

        /// <summary>
        /// 解析二维码
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Decode()
        {
            HttpFileCollection files = HttpContext.Current.Request.Files;
            if (files.Count > 0)
            {
                HttpPostedFile file = files[0];

                //inputstream转Bitmap
                Bitmap b = new Bitmap(file.InputStream);

                //二维码结果
                String qrcode = null;

                BarcodeReader reader = new BarcodeReader();

                //通过reader解码
                //显示用zxing解码,速度快,但识别率不怎么高
                Result result = reader.Decode(b);

                //zxing解码结果
                qrcode = result == null ? null : result.Text;

                if (qrcode == null)
                {
                    try
                    {
                        //尝试换一种方式解码
                        //QRCode  优点:识别率高,缺点:解码速度慢
                        qrcode = new QRCodeDecoder().decode(new QRCodeBitmapImage(new Bitmap(b)));
                    }
                    catch
                    {

                    }
                }

                //依然无法解码,尝试修改图片亮度对比度
                if (qrcode == null)
                {
                    //如果没有识别出二维码,调整图片亮度对比度再识别,循环40次
                    //解决微信个性二维码个别不能识别的BUG
                    for (int i = 0; i < 40; i++)
                    {

                        //去调整亮度对比度
                        BrightnessP(b, -5, 200);

                        //继续解码
                        result = reader.Decode(b);
                        if (result != null)
                        {
                            //解码成功
                            break;
                        }
                    }
                }

                //zxing解码结果
                qrcode = result == null ? null : result.Text;

                //继续解码
                if (qrcode == null)
                {
                    try
                    {
                        //尝试换一种方式解码
                        //QRCode  优点:识别率高,缺点:解码速度慢
                        qrcode = new QRCodeDecoder().decode(new QRCodeBitmapImage(new Bitmap(b)));
                    }
                    catch
                    {

                    }
                }

                if (qrcode != null)
                {
                    Success(qrcode);
                }
                else
                {
                    //实在是无法识别
                    JsonResult(11, "无法识别您的二维码");
                }
            }
            Fail();
        }


        //定义数字图象处理之（亮度调整函数）
        /// <summary>
        /// 改变图片的亮度对比度
        /// </summary>
        /// <param name="b">bitmap对象</param>
        /// <param name="degree">每次改变的数量</param>
        /// <param name="maxRGB">rgb最大阈值</param>
        /// <returns></returns>
        private void BrightnessP(Bitmap b, int degree, int maxRGB)
        {
            if (degree < -255) degree = -255;
            if (degree > 255) degree = 255;

            int width = b.Width;
            int height = b.Height;

            int pix = 0;

            BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            unsafe
            {
                byte* p = (byte*)data.Scan0;
                int offset = data.Stride - width * 3;
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        // 处理指定位置像素的亮度
                        for (int i = 0; i < 3; i++)
                        {
                            if (p[i] > maxRGB)
                            {
                                continue;
                            }

                            pix = p[i] + degree;

                            if (degree < 0) p[i] = (byte)Math.Max(0, pix);
                            if (degree > 0) p[i] = (byte)Math.Min(255, pix);

                        } // i
                        p += 3;
                    } // x
                    p += offset;
                } // y
            }

            b.UnlockBits(data);
        }
    }
}